#!/usr/bin/env python

import os
import sys
import argparse
import time
import stat
import signal
import logging


parser = argparse.ArgumentParser(description='monitor')
parser.add_argument('--file', dest='file', help='will monitor file or director')
parser.add_argument('--pid', dest='pid', type=int, help='send SIGHUP signal to process')

args = parser.parse_args()


if args.file is None or args.pid is None:
    parser.print_help()
    sys.exit(1)


if not os.path.exists(args.file):
    print('file {0} not exits'.format(args.file))
    sys.exit(1)


logger = logging.getLogger("monitor")
stream = logging.StreamHandler()
stream.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream.setFormatter(formatter)
logger.addHandler(stream)


def get_last_mtime(file):
    statinfo = os.stat(args.file)
    mtime = statinfo.st_mtime
    return mtime

def restart(pid):
    os.kill(pid, signal.SIGHUP)



last_mtime = get_last_mtime(args.file)
while True:
    time.sleep(1)
    mtime = get_last_mtime(args.file)
    if mtime != last_mtime:
        logger.info("file %s has changed, will call process %s", args.file, args.pid)
        last_mtime = mtime
        restart(args.pid)

